const Cesium = DE.__namespace.Cesium

const DEFAULT_SATELLITE_MODE_URL = "model/weixing.gltf"

let arrStates = []
let start, stop, viewer

export function simulation(v, startTime, endTime) {
  viewer = v
  // start = new Cesium.JulianDate.fromDate(new Date()); // 获取当前时间 这不是国内的时间
  start = new Cesium.JulianDate.fromDate(startTime) // 获取当前时间 这不是国内的时间
  stop = new Cesium.JulianDate.fromDate(endTime) // 获取当前时间 这不是国内的时间
  // console.log(start)
  const sec = stop.secondsOfDay - start.secondsOfDay
  // start = Cesium.JulianDate.addHours(start, 8, new Cesium.JulianDate()); // 添加八小时，得到我们东八区的北京时间
  // stop = Cesium.JulianDate.addHours(stop, 8, new Cesium.JulianDate()); // 设置一个结束时间，意思是360秒之后时间结束

  viewer.clock.startTime = start.clone() // 给cesium时间轴设置开始的时间，也就是上边的东八区时间
  viewer.clock.stopTime = stop.clone() // 设置cesium时间轴设置结束的时间
  viewer.clock.currentTime = start.clone() // 设置cesium时间轴设置当前的时间
  viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP // 时间结束了，再继续重复来一遍
  // 时间变化来控制速度 // 时间速率，数字越大时间过的越快
  viewer.clock.multiplier = 2
  // 给时间线设置边界
  viewer.timeline.zoomTo(start, stop)

  arrStates = []
  getRandState(arrStates, 1, sec)
  startFunc()
}

function mySatePosition() {
  this.lon = 0
  this.lat = 0
  this.hei = 700000 // 卫星高度
  this.phei = 700000 / 2 // 轨道高度
  this.time = 0
}

function computeCirclularFlight(source, panduan) {
  const property = new Cesium.SampledPositionProperty()
  if (panduan === 1) {
    // 卫星位置
    for (let i = 0; i < source.length; i++) {
      const time = Cesium.JulianDate.addSeconds(start, source[i].time, new Cesium.JulianDate())
      const position = Cesium.Cartesian3.fromDegrees(source[i].lon, source[i].lat, source[i].hei)
      // 添加位置，和时间对应
      property.addSample(time, position)
    }
  } else if (panduan === 2) {
    // 轨道位置
    for (let i = 0; i < source.length; i++) {
      const time = Cesium.JulianDate.addSeconds(start, source[i].time, new Cesium.JulianDate())
      const position = Cesium.Cartesian3.fromDegrees(source[i].lon, source[i].lat, source[i].phei)
      // 添加位置，和时间对应
      property.addSample(time, position)
    }
  }
  return property
}

function getRandState(brr, count, sec) {
  for (let m = 0; m < count; m++) {
    const arr = []
    const t1 = Math.floor(Math.random() * sec)
    const t2 = Math.floor(Math.random() * sec)
    for (let i = t1; i <= sec + t1; i += 30) {
      const aaa = new mySatePosition()
      aaa.lon = t2
      aaa.lat = i
      aaa.time = i - t1
      arr.push(aaa)
    }
    brr.push(arr)
  }
  // console.log(brr)
}

function getStatePath(aaa) {
  // console.log(aaa)
  // console.log(viewer)

  const entity_ty1p = computeCirclularFlight(aaa, 2)
  const entity_ty1 = viewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: start,
        stop: stop
      })
    ]),
    position: entity_ty1p, // 轨道高度
    orientation: new Cesium.VelocityOrientationProperty(entity_ty1p),
    cylinder: {
      HeightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      length: 700000,
      topRadius: 0,
      bottomRadius: 900000 / 2,
      // material: Cesium.Color.RED.withAlpha(.4),
      // outline: !0,
      numberOfVerticalLines: 0,
      // outlineColor: Cesium.Color.RED.withAlpha(.8),
      material: Cesium.Color.fromBytes(35, 170, 242, 80)
    }
  })

  entity_ty1.position.setInterpolationOptions({
    interpolationDegree: 5,
    interpolationAlgorithm: Cesium.LagrangePolynomialApproximation
  })

  const entity1p = computeCirclularFlight(aaa, 1)
  // 创建实体
  const entity1 = viewer.entities.add({
    // 将实体availability设置为与模拟时间相同的时间间隔。
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: start,
        stop: stop
      })
    ]),
    position: entity1p, // 计算实体位置属性
    // 基于位置移动自动计算方向.
    orientation: new Cesium.VelocityOrientationProperty(entity1p),
    // 加载飞机模型
    model: {
      uri: DEFAULT_SATELLITE_MODE_URL,
      scale: 30000
    },
    // 路径
    path: {
      resolution: 1,
      material: new Cesium.PolylineGlowMaterialProperty({
        glowPower: 0.1,
        color: Cesium.Color.PINK
      }),
      width: 5
    }
  })

  // 差值器
  entity1.position.setInterpolationOptions({
    interpolationDegree: 5,
    interpolationAlgorithm: Cesium.LagrangePolynomialApproximation
  })
}

function startFunc() {
  for (let i = 0; i < arrStates.length; i++) {
    getStatePath(arrStates[i])
  }
}

export function scanning(czml, layer) {
  console.log(viewer.clock.currentTime)

  const cylinderEntity = new DE.Cylinder("-105.0, 40.0, 2000000.0", 4000000, 0.0, 2000000.0)
  // cylinderEntity.setStyle("red")
  // const cylinderEntity = viewer.entities.add({
  //   name: "Red cone",
  //   position: Cesium.Cartesian3.fromDegrees(-105.0, 40.0, 200000.0),
  //   cylinder: {
  //     length: 400000.0,
  //     topRadius: 0.0,
  //     bottomRadius: 200000.0,
  //     material: Cesium.Color.RED.withAlpha(0.5)
  //   }
  // })

  const vectorLayer = new DE.VectorLayer("vectorLayer")
  viewer.addLayer(vectorLayer)
  vectorLayer.addOverlay(cylinderEntity)

  const dataSource = layer.delegate
  if (dataSource.then) {
    dataSource.then((_dataSource) => {
      changeCylinderPosition(_dataSource, cylinderEntity)
    })
  } else {
    changeCylinderPosition(dataSource, cylinderEntity)
  }
}

const changeCylinderPosition = (dataSource, cylinderEntity) => {
  const satellite = dataSource.entities.getById("QingHe1")
  console.log(satellite)
  const property = new Cesium.SampledPositionProperty()
  const currentTime = satellite.availability.start
  for (let ind = 0; ind < 292; ind++) {
    const time = Cesium.JulianDate.addSeconds(currentTime, 300 * ind, new Cesium.JulianDate())
    const position = satellite.position.getValue(time)
    console.log(position)
    if (position) {
      const cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position)
      const lat = Cesium.Math.toDegrees(cartographic.latitude)
      const lng = Cesium.Math.toDegrees(cartographic.longitude)
      const hei = cartographic.height / 1.9
      property.addSample(time, Cesium.Cartesian3.fromDegrees(lng, lat, hei))
    }
  }

  cylinderEntity.delegate.position = property
  cylinderEntity.delegate.position.setInterpolationOptions({
    // 设定位置的插值算法
    interpolationDegree: 5,
    interpolationAlgorithm: Cesium.LagrangePolynomialApproximation
  })
}
